import * as THREE from 'three';
import { GLTFLoader } from 'three/examples/jsm/loaders/GLTFLoader.js';

function resizeImage(image) {
    // console.log('resizeImage -> ', image);
    const scale = 1;
    console.log("image.width===============" + image.width);
    const width = THREE.MathUtils.floorPowerOfTwo(scale * image.width);
    const height = THREE.MathUtils.floorPowerOfTwo(scale * image.height);
    if (width === image.width && height === image.height) return image;
    if (
        (typeof HTMLImageElement !== 'undefined' && image instanceof HTMLImageElement) ||
        (typeof HTMLCanvasElement !== 'undefined' && image instanceof HTMLCanvasElement) ||
        (typeof ImageBitmap !== 'undefined' && image instanceof ImageBitmap)
    ) {
        document.createElementNS('http://www.w3.org/1999/xhtml', 'canvas');
        const canvas = document.createElementNS('http://www.w3.org/1999/xhtml', 'canvas');
        canvas.width = width;
        canvas.height = height;
        const context = canvas.getContext('2d');
        context.drawImage(image, 0, 0, width, height);
        return canvas;
    } else {
        return image;
    }
}

function resizeAllImages(obj) {
    // console.log('resizeAllImages => ', obj);
    obj.traverse(o => {
        if (o.material) {
            if (o.material.map && o.material.map.image) {
                // console.log('1 => ', o);
                o.material.map.image = resizeImage(o.material.map.image);
            } else if (o.material.length > 1) {
                o.material.forEach(m => {
                    if (m.map && m.map.image) {
                        // console.log('2 => ', o);
                        m.map.image = resizeImage(m.map.image);
                    }
                });
            }
        }
    });
}

export async function loadGltfAsync(path) {
    return new Promise((resolve, reject) => {
        const loader = new GLTFLoader();
        loader.load(
            path,
            gltf => {
                // resolve(gltf.scene);

                // Reference: https://stackoverflow.com/questions/55175351/remove-texture-has-been-resized-console-logs-in-three-js
                // To resolve 'THREE.WebGLRenderer: Texture has been resized from xx to xx'.
                setTimeout(() => {
                    resizeAllImages(gltf.scene);
                    resolve(gltf);
                }, 0);
            },
            null,
            e => {
                reject(e);
            }
        );
    });
}

export async function loadFontAsync(file) {
    return new Promise((resolve, reject) => {
        const loader = new THREE.FontLoader();
        // const loader = new TTFLoader();
        loader.load(
            file,
            f => {
                resolve(f);
                // resolve(new THREE.Font(f));
            },
            null,
            e => reject(e)
        );
    });
}
